Java Fundamentals

Parts of a Java Program


Semi-colons in Java

Java statements, curly braces, comments, and Java framework code don’t need semicolons.

Console Output and Stdio

The console window displays only text.

System.out.println("Programming is fun!");

The standard input device is typically the keyboard

Java Escape Characters

CharNameDescription
\nnewlineAdvances cursor to next line
\ttabCauses cursor to skip to next tab stop
\bbackspaceCauses cursor to back up, or move left, one position
\rcarriage returnCauses cursor to go to beginning of current line
\\backslashCauses a backslash to be printed
\'single quoteCauses a single quotation mark to be printed
\"double quoteCauses a double quotation mark to be printed

With these escape sequences, complex text output can be achieved.

Variables and Literals

public class Variable
{
    public static void main(String[] args)
    {
        int value; // Variable declaration

        value = 5; // Assignment statement (stores '5' in memory)
        System.out.print("The value is "); // "The value is " is a string literal
        System.out.println(value); // Prints the integer '5'
    }
}

The + Operator

+ can be used two ways:

  1. As an addition operator
  2. As a concatenation operator

Warnings on String Literals:

Identifiers

Identifiers: Programmer-defined names that represent classes, variables, or methods

Naming Conventions:

Primitive Data Type

Primitive Data Type: The type of data the variable can hold

Numeric Data Types: | Name | Size | Range | | — | — | — | | byte | 1 byte | Integers in range -128 to 127 | | short | 2 bytes | Integers in the range -32768 to 32767 | | int | 4 bytes | Integers in the range -2147483648 to 2147483647 | | long | 8 bytes | Integers in the range -9223372036854775808 to 9223372036854775807 | | float | 4 bytes | | | double | 8 bytes | |

Tip: You can declare several variables of the same type like so:

int length, width, area

Floating Point Data Types

Data types that allow fractional values.

Java Floating-Point Data Types:

Note: Remember to append F to a float.

boolean Data Type

Can have two possible values: true or false.

boolean bool;
bool = true;

char Data Typ

Provides access to single characters

char letter;
letter = 'A';

Unicode

char letter = 65;
System.out.println(letter); // Prints 'A'

Constants with final

Variables whose value cannot be changed (read-only).

final double INTEREST_RATE = 0.069;

The Scanner Class

Defined in java.util, allows reading input from the keyboard.

Imported like so:

import java.util.Scanner;

Scanner objects work with System.in, the standard input device.

// Create Scanner object
Scanner keyboard = new Scanner(System.in);

Scanner class methods to return input as a …:

Note: Remember to close a Scanner object to prevent memory leaks.

Variable Assignment and Initialization

Assignment Operator (=): Stores a value in a variable

More on variables:

Binary Arithmetic Operators

Java has five arithmetic operators: | Operator | Meaning | | — | — | | + | Addition | | - | Subtraction | | * | Multiplication | | / | Division | | % | Modulus |

Unary and Ternary Operators

OperatorMeaning
-Negation

Integer Division

Integer division is truncated. Pay attention to types.

e.g.,

double number = 5/2;
System.out.println(number); // Prints "2.0"

number = 5.0/2;
System.out.println(number); // Prints "2.5"

Operator Precedence

OperatorAssociativityExampleResult
-Right to leftx = -4 + 3-1
* / %Left to rightx = -4 + 4 % 3 * 13 + 211
+ -Left to rightx = 6 + 3 - 4 + 6 * 323

Grouping with Parenthesis

Math Class

Java’s Math class contains useful methods for complex mathematical operations. e.g.,

Predefined \pi:

Combined Assignment Operators

Allow programmer to perform arithmetic and assignment with a single operator.

OperatorExample
+=x+=5
-=y-=2
*=z*=10
/=a /=b
%=c %=3

Conversion between Primitive Data Types

Java performs some conversions between data types automatically if the conversion will not result in the loss of data.

int x;
double y = 2.5;
x = y; // Compile error! (data loss)
int x;
short y = 2;
x = y; // This is fine

Ranking of numeric data types (Java automatically converts smaller to larger, this is called the widening operation):

Cast Operator

If you need to perform the narrowing conversion, you need to use the cast operator.

TARGET_DATA_TYPE x = (TARGET_DATA_TYPE) number;

Promotion

Java performs promotion automatically when operands are of different data types.

The String Class

String is not a primitive data type, it is a class from the Java standard library.

Primitive vs. Class Type Variables

Primitive variables actually contain the value they’ve been assigned.

Objects (instances of classes) aren’t stored in variables. Objects are referenced by variables.

String Objects

Scope

Scope: The part of a program that has access to a variable’s contents.

Commenting Code and Javadoc

StyleDescription
//Single line comment.
/* ... */Block comment.
/** ... */Javadoc comment.

Note on Javadoc comments: Allows comments to be documented by the javadoc utility. Can be built into HTMl documentation.

Programming Style

Although the compiler doesn’t care about white space, humans do!

Indentation

Programs should use proper indentation.

Dialog Boxes

Dialog Boxes: Small graphical window that displays a message to the user or requests input.

The Parse Methods

Parse Methods: Method that converts a String to a number.

int x = Integer.parseInt("2599");
float y = Float.parseFloat("12.3");
// etc...